"""
断言处理工具类
"""
import json
from loguru import logger
from api_test_framework.utils.handle_mysql import HandleMysql
from api_test_framework.utils.handle_replace import replace_mark_data
from api_test_framework.config.settings import DB_CONFIG

def db_assert(assert_data):
    """
    数据库断言
    :param assert_data: 断言数据，格式如：{"sql语句": 预期结果}
    """
    if assert_data is None:
        logger.info("本条用例不需要做数据库断言！")
        return

    assert_data = replace_mark_data(assert_data)
    assert_data = json.loads(assert_data)
    logger.info(f"数据库断言的表示式：{assert_data}")
    for s_sql, s_expect in assert_data.items():
        sql_result = HandleMysql(**DB_CONFIG).query_data(s_sql)
        for i in sql_result.values():
            logger.info(f"数据库的查询的实际结果是：{i}, 预期：{s_expect}")
            try:
                assert i == s_expect
                logger.info("数据库断言成功")
            except AssertionError as err:
                logger.error(f"数据库断言失败，失败原因是：{err}")
                raise err


if __name__ == '__main__':
    assert_data = """{"select count(1) from tz_order where order_number = '#orderNumbers#'":1,
                    "select status from tz_order where order_number = '#orderNumbers#'":1}"""
    db_assert(assert_data) 